package com.jishuo.nontax.bfc.service;

import com.github.pagehelper.PageHelper;
import com.jishuo.base.bean.BaseResult;
import com.jishuo.base.bean.ErrorCodeEnum;
import com.jishuo.base.bean.Pagination;
import com.jishuo.base.bean.vo.UserVO;
import com.jishuo.base.config.NonTaxConfig;
import com.jishuo.base.dao.UserMapper;
import com.jishuo.base.service.SequenceService;
import com.jishuo.base.util.CommonUtil;
import com.jishuo.base.util.GTimeUtil;
import com.jishuo.base.util.StringUtil;
import com.jishuo.nontax.bean.bank.NewItemDTO;
import com.jishuo.nontax.bean.bank.*;
import com.jishuo.nontax.bean.message.*;
import com.jishuo.nontax.bean.vo.*;
import com.jishuo.nontax.bfc.dao.*;
import com.jishuo.nontax.bfc.tlq.MessageFactory;
import com.jishuo.nontax.bfc.tlq.MessageService;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @auther dinggaofei
 * @Date 2022/12/13 8:42
 */
@Service
public class BaseDataService {

    private static Logger logger = LoggerFactory.getLogger(BaseDataService.class);
    @Resource
    private StatDataMapper statDataMapper;
    @Resource
    private BaseDataMapper baseDataMapper;
    @Resource
    private SequenceService sequenceService;
    @Resource
    private BankMapper bankMapper;
    @Resource
    private MessageService messageService;
    @Resource
    private NonTaxConfig nonTaxConfig;
    @Resource
    private CantonMapper cantonMapper;
    @Resource
    private UnitMapper unitMapper;
    @Resource
    private BillTypeMapper billTypeMapper;

    /**
     * @author hlp
     * @date 2023/2/10 15:38
     * @Description:
     */
    public BankVO findBankVO(String accountcode) {
        return bankMapper.findBankVO(accountcode);
    }

    public BankStationVO getBankStation(long stationid) {
        return baseDataMapper.getBankStation(stationid);
    }


    public List<CantonVO> findCantonPage(Pagination pagination) {
        // 当单页条数大于零时，启用分页
        if (pagination.getRows() > 0) PageHelper.startPage(pagination.getPage(), pagination.getRows());
        return cantonMapper.findCantonPage();
    }

    public List<UnitVO> findUnitPage(Long cantonid,Pagination pagination) {
        // 当单页条数大于零时，启用分页
        if (pagination.getRows() > 0) PageHelper.startPage(pagination.getPage(), pagination.getRows());
        return unitMapper.findUnitVO(cantonid);
    }


    public List<ItemVO> findItemPage(Long cantonid,Long unitid,Pagination pagination) {
        // 当单页条数大于零时，启用分页
        if (pagination.getRows() > 0) PageHelper.startPage(pagination.getPage(), pagination.getRows());
        return itemMapper.findItem(cantonid,unitid);
    }

    public List<BillTypeVO> findBillTypePage(Pagination pagination) {
        // 当单页条数大于零时，启用分页
        if (pagination.getRows() > 0) PageHelper.startPage(pagination.getPage(), pagination.getRows());
        return billTypeMapper.findBillType();
    }

    public List<BankVO> findBankPage(Long cantonid, Pagination pagination) {
        // 当单页条数大于零时，启用分页
        if (pagination.getRows() > 0) PageHelper.startPage(pagination.getPage(), pagination.getRows());
        return bankMapper.findBankView(nonTaxConfig.Sender,cantonid);
    }

    public List<AreaVO> findBankList(Long cantonid) {
        List<BankVO> bankView = bankMapper.findBankView(nonTaxConfig.Sender, cantonid);
        List<AreaVO> areaVOS = new ArrayList<>();
        for (BankVO bankVO : bankView) {
            AreaVO areaVO = new AreaVO();
            areaVO.setId(bankVO.getBankid().toString());
            areaVO.setAcode(bankVO.getAccountcode());
            areaVO.setText(bankVO.getBankid()+"||"+bankVO.getAccountcode()+"||"+bankVO.getAccountname()+"||"+bankVO.getBankname());
            areaVOS.add(areaVO);
        }
        return areaVOS;
    }

    public List<BankVO> findBankBystatePage(UserVO user) {
        long[] bankids = CommonUtil.getIdsLong(user.getBankId(), ";");
        if ("3".equals(user.getRole())) {
            return bankMapper.findBankBystate(nonTaxConfig.Sender, null, null);
        }
        return bankMapper.findBankBystate(nonTaxConfig.Sender, user.getCantonId(), bankids.length == 0 ? null : bankids);
    }

    public List<BankStationVO> findBankStationPage(Long cantonid, Pagination pagination) {
        if (pagination.getRows() > 0) PageHelper.startPage(pagination.getPage(), pagination.getRows());
        return baseDataMapper.findBankStationView(cantonid, 0);
    }

    public List<PayWayVO> findPayWayPage(Pagination pagination) {
        if (pagination.getRows() > 0) PageHelper.startPage(pagination.getPage(), pagination.getRows());
        return baseDataMapper.findPayWay();
    }

    /** 根据网点，获得行政区划 */
    public List<AreaVO> findCantonMapInStation() {
        List<BankStationVO> banks = baseDataMapper.findBankStationView(null, 1);
        String cans = "";
        for (BankStationVO vo : banks) {
            cans += "," + vo.getCantoncode();
        }
        List<CantonVO> all = cantonMapper.findCanton();
        List<AreaVO> ret = new ArrayList<>();
        AreaVO a1 = new AreaVO();
        AreaTwoVO a2 = null;
        for (CantonVO vo : all) {
            if ("130000".equals(vo.getCantoncode())) {
                a1.setId(StringUtil.toStr(vo.getCantonid()));
                a1.setAcode(vo.getCantoncode());
                a1.setText(vo.getCantoncode() + "-" + vo.getCantonname());
            } else if ("3".equals(vo.getCantonlevel())) {
                if (cans.indexOf("," + vo.getCantoncode().substring(0, 4)) < 0) continue;
                if (a1.getChildren() == null) a1.setChildren(new ArrayList<>());
                AreaTwoVO aa = new AreaTwoVO();
                aa.setId(StringUtil.toStr(vo.getCantonid()));
                aa.setAcode(vo.getCantoncode());
                aa.setText(vo.getCantoncode() + "-" + vo.getCantonname());
                aa.setState("open");
                a1.getChildren().add(aa);
                a2 = aa;
            } else if ("4".equals(vo.getCantonlevel())) {
                if (cans.indexOf("," + vo.getCantoncode()) < 0) continue;
                if (a2.getChildren() == null) a2.setChildren(new ArrayList<>());
                AreaThreeVO a3 = new AreaThreeVO();
                a3.setId(StringUtil.toStr(vo.getCantonid()));
                a3.setAcode(vo.getCantoncode());
                a3.setText(vo.getCantoncode() + "-" + vo.getCantonname());
                a2.getChildren().add(a3);
            }
        }
        ret.add(a1);
        return ret;
    }

    /** 获得全部区划 */
    public List<AreaVO> findAllCantonMap() {
        List<CantonVO> all = cantonMapper.findCanton();
        List<AreaVO> ret = new ArrayList<>();
        AreaVO a1 = new AreaVO();
        a1.setChildren(new ArrayList<>());
        AreaTwoVO a2 = null;
        for (CantonVO vo : all) {
            if ("130000".equals(vo.getCantoncode())) {
                a1.setId(StringUtil.toStr(vo.getCantonid()));
                a1.setAcode(vo.getCantoncode());
                a1.setText(vo.getCantoncode() + "-" + vo.getCantonname());
            } else if ("3".equals(vo.getCantonlevel())) {
                AreaTwoVO aa = new AreaTwoVO();
                aa.setId(StringUtil.toStr(vo.getCantonid()));
                aa.setAcode(vo.getCantoncode());
                aa.setText(vo.getCantoncode() + "-" + vo.getCantonname());
                aa.setChildren(new ArrayList<>());
                a1.getChildren().add(aa);
                a2 = aa;
            } else if ("4".equals(vo.getCantonlevel())) {
                AreaThreeVO a3 = new AreaThreeVO();
                a3.setId(StringUtil.toStr(vo.getCantonid()));
                a3.setAcode(vo.getCantoncode());
                a3.setText(vo.getCantoncode() + "-" + vo.getCantonname());
                a2.getChildren().add(a3);
            }
        }
        ret.add(a1);
        return ret;
    }
    public List<CantonVO> findCantonView(UserVO userVO) {
        userVO.setBankcls(nonTaxConfig.Sender);
        return cantonMapper.findUserCanton(userVO);
    }

    public List<AreaVO> findCantonMapView(UserVO userVO) {
        userVO.setBankcls(nonTaxConfig.Sender);
        return cantonMapper.findUserCantonMap(userVO);
    }

    public List<BankStationVO> findBankStationView(Long cantonid){
        return baseDataMapper.findBankStationView(cantonid, 1);
    }

    public List<BankStationVO> findStationCancode(String cantoncode){
        return baseDataMapper.findStationCancode(cantoncode);
    }

    public BaseResult deleteBankstation(long bankstationid){
        if(baseDataMapper.updateBankStationIsenable(bankstationid) > 0){
            return new BaseResult();
        }
        return new BaseResult(ErrorCodeEnum.DB_ERR);
    }

    public List<PayWayVO> findPayWayView() {
        return payWayMapper.findPayWayView();
    }

    /**
     * 查询账户列表，根据用户
     * @param userVO 登录用户
     * @return
     */
    public List<BankVO> findBankView(UserVO userVO) {
        String[] split = userVO.getRole().split(",");
        for (String s : split) {
            if("3".equals(s)) {
                // 超级管理员，查看所有
                return bankMapper.findBankView(nonTaxConfig.Sender,null);
            }
        }
        // 根据用户
        if(StringUtil.isNotEmpty(userVO.getBankId())) {
            // 根据用户赋予的管理账户
            return bankMapper.findUserBankView(nonTaxConfig.Sender,userVO.getBankId());
        } else {
            // 根据用户区划
            return bankMapper.findBankView(nonTaxConfig.Sender,userVO.getCantonId());
        }
    }

    @Resource
    private UserMapper userMapper;

    public BaseResult sendBankStation(Long cantonid,String usercode,String userpwd){
        if(userMapper.getUserCount(userpwd, usercode)>0){
            if(cantonid!=null){
                return sendBankStation(cantonid);
            }
        }
        return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR);
    }

    /**
     * @auther dinggaofei
     * @Date 2022/12/13 9:12
     * @description 查询缴款方式，返回全部可用的缴款方式
     */
    public BaseResult findPayWay() {
        try {
            ArrayList<PayWayVO> list = baseDataMapper.findPayWay();
            if (list != null && list.size() > 0) {
                ArrayList<PayWay> payWay = MessageFactory.getPayWay(list);
                //xml解析器
                Serializer serializer = new Persister();
                //xml转换器
                StringWriter sw = new StringWriter();
                PayWayXml xml = new PayWayXml();
                xml.setPayway(payWay);
                serializer.write(xml, sw);
                return new BaseResult(sw.toString());
            } else {
                return new BaseResult("<bills></bills>");
            }

        } catch (Exception e) {
            logger.info("处理获取缴款书失败：" + e.toString());
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR, "<bills></bills>");
        }
    }

    /**
     * @param unitid 单位ID
     * @auther dinggaofei
     * @Date 2022/12/13 9:38
     * @description 按照单位信息获取缴费类型的业务场景，暂时只会在批扣中用到，未来可能延伸到电子票据和网上缴费业务。
     */

    public BaseResult findPayerType(int unitid) {

        try {
            ArrayList<PayerType> list = baseDataMapper.findPayerType(unitid);
            //查询返回记录
            if (list != null && list.size() > 0) {
                //xml解析器
                Serializer serializer = new Persister();
                //xml转换器
                StringWriter sw = new StringWriter();
                PayerTypeXml xml = new PayerTypeXml();
                xml.setPayertype(list);
                serializer.write(xml, sw);
                return new BaseResult(sw.toString());
            } else {
                return new BaseResult("<bills></bills>");
            }
        } catch (Exception e) {
            logger.info("处理获取缴费类型失败：" + e.toString());
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR, "<bills></bills>");
        }
    }

    /**
     * @auther dinggaofei
     * @Date 2022/12/13 9:50
     * @description 获取可用的字轨信息给代理银行的业务场景
     */

    public BaseResult findKeyword() {
        try {
            ArrayList<KeyWord> list = baseDataMapper.findKeyword();
            //查询返回记录
            if (list != null && list.size() > 0) {
                //xml解析器
                Serializer serializer = new Persister();
                //xml转换器
                StringWriter sw = new StringWriter();
                KeywordXml xml = new KeywordXml();
                xml.setKeyword(list);
                serializer.write(xml, sw);
                return new BaseResult(sw.toString());
            } else {
                return new BaseResult("<bills></bills>");
            }
        } catch (Exception e) {
            logger.info("失败：" + e.toString());
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR, "<bills></bills>");
        }
    }

    /**
     * @auther dinggaofei
     * @Date 2022/12/13 10:01
     * @description 获取可用的行政区划信息给代理银行的业务场景
     */
    public BaseResult findCanton() {

        try {
            ArrayList<Canton> list = baseDataMapper.findCanton(nonTaxConfig.Sender);
            //查询返回记录
            if (list != null && list.size() > 0) {
                //xml解析器
                Serializer serializer = new Persister();
                //xml转换器
                StringWriter sw = new StringWriter();
                CantonXml xml = new CantonXml();
                xml.setCanton(list);
                serializer.write(xml, sw);
                return new BaseResult(sw.toString());
            } else {
                return new BaseResult("<bills></bills>");
            }
        } catch (Exception e) {
            logger.info("失败：" + e.toString());
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR, "<bills></bills>");
        }
    }

    public void sysSETBILLTYPE(String data){
        //xml解析器
        Serializer serializer = new Persister();
        try{
            //票据种类信息对象
            SetBillType setbilltype = serializer.read(SetBillType.class, new StringReader(data));
            if(setbilltype!=null && setbilltype.getBilltype()!=null && setbilltype.getBilltype().size()>0){
                for(SetBillTypeDTO billtype:setbilltype.getBilltype()){
                    if(billtype!=null && billtype.getState()!=null && !billtype.getState().trim().equals("") && billtype.getBilltypeid()!=null && !billtype.getBilltypeid().trim().equals("")){
                        BillTypeVO billTypeVO = new BillTypeVO(billtype);
                        billTypeVO.setIsenable(1);
                        billTypeVO.setWritetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                        if(billtype.getState().trim().equals("1")){
                            if(billTypeMapper.selectBillTypeCount(billTypeVO.getBilltypeid())>0){
                                billTypeMapper.updateIsenable(billTypeVO);
                            }else{
                                billTypeMapper.saveBillType(billTypeVO);
                            }
                            break;
                        }else if (billtype.getState().trim().equals("2")){
                            billTypeMapper.updateBillType(billTypeVO);
                            break;
                        }else if (billtype.getState().trim().equals("3")){
                            billTypeVO.setIsenable(0);
                            billTypeMapper.updateIsenable(billTypeVO);
                            break;
                        }

                    }
                }
            }
        }catch(Exception e){
            logger.info("分析处理基础信息的票据种类失败"+e.toString());
        }
    }

    /**
     * bankcls  银行类别
     *
     * @param cantonid 行政区划
     * @auther dinggaofei
     * @Date 2022/12/13 11:02
     * @description 获取可用的银行账户信息给代理银行的业务场景
     */
    public BaseResult findBank(Long cantonid) {
        try {
            ArrayList<Bank> list = bankMapper.findBank(nonTaxConfig.Sender, cantonid);
            if (list != null && list.size() > 0) {
                //xml解析器
                Serializer serializer = new Persister();
                //xml转换器
                StringWriter sw = new StringWriter();
                BankXml xml = new BankXml();
                xml.setBank(list);
                serializer.write(xml, sw);
                return new BaseResult(sw.toString());
            } else {
                return new BaseResult("<bills></bills>");
            }
        } catch (Exception e) {
            logger.info("失败：" + e.toString());
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR, "<bills></bills>");
        }
    }

    public List<BankVO> findBankVoView(Long cantonid){
        return bankMapper.findBankVoView(nonTaxConfig.Sender, cantonid);
    }


    /**
     * bank
     *
     * @auther dinggaofei
     * @Date 2022/12/15 8:45
     * @description 修改代理银行账户信息
     */
    public BaseResult confirmBankManage(BankVO bankVO) {
        try {

            if (bankVO.getOperate() == 1 || bankVO.getOperate() == 2) {
                bankVO.setIsenable(1);
            } else {
                bankVO.setIsenable(0);
            }
            if (bankMapper.setBank(bankVO) > 0) {
                return sendBankManage(bankVO.getBankid());
            }
            return BaseResult.CustomErr("更新失败");
        } catch (Exception e) {
            logger.info("发送回执失败：" + e.toString());
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR);
        }
    }

    /**
     * @param bankid
     * @auther dinggaofei
     * @Date 2022/12/15 9:30
     * @description 根据bankid查询银行账户信息
     */
    public BaseResult sendBankManage(Long bankid) {
        try {
            ArrayList<BankVO> list = bankMapper.findBankByBankid(bankid);
            if (list != null && list.size() > 0) {
                SetBank setBank = new SetBank();
                ArrayList<SetBankDTO> bankList = new ArrayList<>();
                for (BankVO vo : list) {
                    SetBankDTO dto = new SetBankDTO();
                    dto.setBankid(StringUtil.toStr(vo.getBankid()));
                    dto.setCantonid(StringUtil.toStr(vo.getCantonid()));
                    dto.setAccountcode(vo.getAccountcode());
                    dto.setAccountname(vo.getAccountname());
                    dto.setBankname(vo.getBankname());
                    dto.setBanklinenum(vo.getBanklinenum());
                    dto.setBankcode(vo.getBankcode());
                    dto.setBankcls(vo.getBankcls());
                    dto.setState(StringUtil.toStr(vo.getOperate()));
                    dto.setMemo(vo.getMemo());
                    bankList.add(dto);
                }
                setBank.setBank(bankList);
                long messageid = sequenceService.getNextSeq("ELEMESSAGESEQ");
                //发送到财政
                messageService.sendMessage("SETBANK", messageid, setBank, "2.0");
            }
            BankVO bank = new BankVO();
            bank.setState(4);
            bank.setBankid(bankid);
            bankMapper.updateBankState(bank);
            return new BaseResult();
        } catch (Exception e) {
            logger.info("发送回执失败：" + e.toString(), e);
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR);
        }
    }


    /**
     * @auther dinggaofei
     * @Date 2022/12/15 14:25
     * @description 添加银行网点
     */
    public BaseResult saveBankStation(BankStationVO bankStationVO) {
        BankStationVO bankStationVO1 = baseDataMapper.selectStationCode(bankStationVO.getBankstationcode(),null);
        if(bankStationVO1 != null){
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR.getCode(),"网点编码已重复");
        }
        try {
            bankStationVO.setBankstationid(sequenceService.getNextSeq("FSBANKSTATIONSEQ"));
        } catch (Exception e) {
            return BaseResult.CustomErr("生成流水号错误");
        }
        if (baseDataMapper.saveBankStation(bankStationVO) > 0){
            return new BaseResult();
        }
        return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR);
    }

    public BaseResult updateBankStation(BankStationVO bankStationVO) {
        BankStationVO bankStationVO1 = baseDataMapper.selectStationCode(bankStationVO.getBankstationcode(),null);
        if(bankStationVO1 != null && bankStationVO1.getBankstationid() == bankStationVO.getBankstationid()){
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR.getCode(),"网点编码已重复");
        }
        if (baseDataMapper.updateBankStation(bankStationVO) > 0) {
            return new BaseResult();
        }
        return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR);
    }

    /**
     * @auther dinggaofei
     * @Date 2022/12/15 14:55
     * @description 根据区域id和网店编码删除银行网点 把状态改成0
     */
    public BaseResult deleteBankStation(int cantonid, String bankstationcode) {
        if (baseDataMapper.deleteBankStation(Integer.toString(cantonid), bankstationcode) > 0) {
            return new BaseResult();
        }
        return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR);
    }

    /**
     * @param cantonid 区域id
     * @auther dinggaofei
     * @Date 2022/12/15 15:40
     * @description 根据区域id 查询银行网点，返回全部可用的银行网点
     */
    public BaseResult findBankStation(int cantonid) {
        try {
            ArrayList<BankStationDTO> list = baseDataMapper.findBankStationBank(cantonid, "1");
            if (list != null && list.size() > 0) {
                //xml解析器
                Serializer serializer = new Persister();
                //xml转换器
                StringWriter sw = new StringWriter();
                BankStation bankstation = new BankStation();
                bankstation.setBankstation(list);
                serializer.write(bankstation, sw);
                return new BaseResult(sw.toString());
            }
            return new BaseResult("<bills></bills>");
        } catch (Exception e) {
            logger.info("失败：" + e.toString());
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR, "<bills></bills>");
        }
    }

    /**
     * @param cantonid 区域id
     * @auther dinggaofei
     * @Date 2022/12/15 14:20
     * @description 根据区域id 向财政发送银行网点
     */
    public BaseResult sendBankStation(Long cantonid) {
        try {
            ArrayList<BankStationVO> list = baseDataMapper.findBankStation(cantonid);

            messageService.sendMessage("SETBANKSTATION", sequenceService.getNextSeq("ELEMESSAGESEQ"), MessageFactory.getSetBankStationDTO(list), "2.0");

            return new BaseResult();
        } catch (Exception e) {
            logger.info("发送网点失败：" + e.toString());
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR);
        }
    }

    public BaseResult sendBankStationById(long bankstationid) {
        try {
            BankStationVO vo = baseDataMapper.getBankStation(bankstationid);
            if (vo == null) return new BaseResult();
            ArrayList<BankStationVO> list = new ArrayList<>();
            list.add(vo);

            messageService.sendMessage("SETBANKSTATION", sequenceService.getNextSeq("ELEMESSAGESEQ"), MessageFactory.getSetBankStationDTO(list), "2.0");

            return new BaseResult();
        } catch (Exception e) {
            logger.info("发送网点失败：" + e.toString());
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR);
        }
    }


    //保存区划月度分析
    public void sysSETSTAT(String data){

        try{
          //xml解析器
          Serializer serializer = new Persister();
          //代理银行信息对象
          SetStatData setStat = serializer.read(SetStatData.class, new StringReader(data));
          if(setStat!=null && setStat.getData()!=null && setStat.getData().size()>0){
            SetStatDataDTO firststat=setStat.getData().get(0);
            statDataMapper.deleteCantonId(firststat.getCantonid(),firststat.getPaybankdt());

            for(SetStatDataDTO stat:setStat.getData()){
                StatDataVO statDataVO = new StatDataVO(stat);
                if(statDataMapper.saveStatData(statDataVO)<=0){
                    break;
                }
            }
        }
        }catch(Exception e){
            logger.info("分析处理基础信息的单位失败"+e.toString());
        }
    }

    //保存业务类型月度分析
    public void sysSETSTAT1(String data){
        try{
            //xml解析器
            Serializer serializer = new Persister();
            //代理银行信息对象
            SetStatData1 setStat1 = serializer.read(SetStatData1.class, new StringReader(data));
            if(setStat1!=null && setStat1.getData()!=null && setStat1.getData().size()>0){
                for(SetStatData1DTO stat:setStat1.getData()){
                    StatDataVO statDataVO = new StatDataVO(stat);
                    if(statDataMapper.selectSetDataCount(statDataVO)>0){
                        statDataMapper.updateSetData(statDataVO);
                    }else{
                        statDataMapper.saveStatData(statDataVO);
                    }

                    break;
                }
            }
        }catch(Exception e){
            logger.info("分析处理基础信息的单位失败"+e.toString());
        }
    }

    public void sysSETCANTON(String data){
        //xml解析器
        Serializer serializer = new Persister();
        try{
            //区划信息对象
            SetCanton setCanton = serializer.read(SetCanton.class, new StringReader(data));

            if(setCanton!=null && setCanton.getCanton()!=null && setCanton.getCanton().size()>0){
                for(SetCantonDTO canton:setCanton.getCanton()){
                    if(canton!=null && canton.getState()!=null && !canton.getState().trim().equals("") && canton.getCantonid()!=null && !canton.getCantonid().trim().equals("")){
                        CantonVO cantonVO = new CantonVO(canton);
                        cantonVO.setWritetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

                        if(canton.getState().trim().equals("1")){
                            //插入行政区划信息
                            cantonVO.setIsenable(0);
                            cantonMapper.saveCantonHis(cantonVO);
                            //根据行政区划编码查询条数
                            if(cantonMapper.selectCantonIdCount(cantonVO.getCantonid())>0){
                                cantonMapper.updateIsenable(cantonVO.getCantonid(),0);
                            }else{
                                cantonVO.setIsenable(1);
                                cantonMapper.saveCanton(cantonVO);
                            }
                            break;
                        }else if (canton.getState().trim().equals("2")){
                            cantonVO.setIsenable(0);
                            cantonMapper.saveCantonHis(cantonVO);

                            if(cantonMapper.selectCantonIdCount(cantonVO.getCantonid())>0){
                                cantonVO.setIsenable(1);
                                cantonMapper.updateCanton(cantonVO);
                            }else{
                                cantonVO.setIsenable(1);
                                cantonMapper.saveCanton(cantonVO);
                            }
                            break;
                        }else if (canton.getState().trim().equals("3")){
                            if(cantonMapper.selectCantonIdCount(cantonVO.getCantonid())>0){
                                cantonMapper.updateIsenable(cantonVO.getCantonid(),1);
                            }else{
                                cantonVO.setIsenable(0);
                                cantonMapper.saveCantonHis(cantonVO);
                                cantonMapper.saveCanton(cantonVO);
                            }
                            break;
                        }
                    }
                }
            }
        }catch(Exception e){
            logger.info("分析处理基础信息的区划失败"+e.toString());
        }
    }

    /**
     * 接收财政，单位数据
     * @param data 报文
     */
    public void sysSETUNIT(String data){
        //xml解析器
        Serializer serializer = new Persister();
        try{
            //代理银行信息对象
            SetUnit  setUnit = serializer.read(SetUnit.class, new StringReader(data));
            if(setUnit!=null && setUnit.getUnit()!=null && setUnit.getUnit().size()>0){
                for(SetUnitDTO unit:setUnit.getUnit()){
                    if(unit!=null && unit.getState()!=null && !unit.getState().trim().equals("") && unit.getUnitid()!=null && !unit.getUnitid().trim().equals("")){
                       //新增和修改
                        UnitVO unitVO = new UnitVO(unit);
                        unitVO.setWritetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                        if ("1".equals(unit.getState()) || "2".equals(unit.getState())) {
                            unitVO.setIsenable(1);
                        } else if ("3".equals(unit.getState())) {
                            unitVO.setIsenable(0);
                        } else {
                            unitVO.setIsenable(null);
                        }
                        if (unitVO.getIsenable() != null) {
                            if(unitMapper.selectUnitIdCount(unitVO.getUnitid())>0){
                                unitMapper.updateUnit(unitVO);
                            }else{
                                unitMapper.saveUnit(unitVO);
                            }
                        }
                    }
                }
            }

        }catch(Exception e){
            logger.info("分析处理基础信息的单位失败"+e.toString(), e);
        }
    }

    public void sysSETBANK(String data){
        //xml解析器
        Serializer serializer = new Persister();
        try{
            //代理银行信息对象
            SetBankDTO bank = serializer.read(SetBankDTO.class, new StringReader(data));
            if(bank!=null && bank.getState()!=null && !bank.getState().trim().equals("") && bank.getBankid()!=null && !bank.getBankid().trim().equals("")){
                BankVO bankVO = new BankVO(bank);
                bankVO.setWritetime(GTimeUtil.getDateTimeMark());
                bankVO.setIsenable(0);
                if (bankVO.getState() == 1) {
                    bankMapper.deleteBankId(bankVO.getBankid());
                    bankMapper.deleteAccountCode(bankVO.getAccountcode());
                    bankMapper.saveBank(bankVO);
                } else if (bankVO.getState() == 2) {
                    bankMapper.updateBank(bankVO);
                } else if (bankVO.getState() == 3) {
                    bankMapper.deleteBank(bankVO);
                }
            }
        }catch(Exception e){
            logger.info("分析处理基础信息的代理银行失败"+e.toString());
        }
    }

    //财政主动推
    public void sysSETBANKS(String data){
        try{
            //xml解析器
            Serializer serializer = new Persister();
            //代理银行信息对象
            SetBank banks = serializer.read(SetBank.class, new StringReader(data));
                for(SetBankDTO bank:banks.getBank()){
                    if(bank!=null && bank.getState()!=null && !bank.getState().trim().equals("") && bank.getBankid()!=null && !bank.getBankid().trim().equals("")){
                        BankVO bankVO = new BankVO(bank);
                        bankVO.setWritetime(GTimeUtil.getDateTimeMark());
                        bankVO.setIsenable(0);
                        if (bankVO.getState() == 1) {
                            bankMapper.deleteBankId(bankVO.getBankid());
                            bankMapper.deleteAccountCode(bankVO.getAccountcode());
                            bankMapper.saveBank(bankVO);
                        } else if (bankVO.getState() == 2) {
                            bankMapper.updateBank(bankVO);
                        } else if (bankVO.getState() == 3) {
                            bankMapper.deleteBank(bankVO);
                        }
                    }
                }
        }catch(Exception e){
            logger.info("分析处理基础信息的代理银行失败"+e.toString());
        }
    }

    @Resource
    private ItemMapper itemMapper;

    //保存项目信息
    public void sysNEWITEM(String data){
        //xml解析器
        Serializer serializer = new Persister();

        try{
            NewItemDTO nitem = serializer.read(NewItemDTO.class, new StringReader(data));
            if(nitem!=null && nitem.getItemid()!=null && !nitem.getItemid().trim().equals("")){
                String operate = nitem.getOperate();
                ItemVO itemVO = new ItemVO(nitem);
                itemVO.setWritetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                itemVO.setIsenable(1);
                if("1".equals(operate)){
                    itemMapper.saveItemHis(itemVO);
                    itemMapper.deleteItemid(itemVO.getItemid());
                    itemMapper.saveItem(itemVO);
                }else if("2".equals(operate)){
                    itemMapper.saveItemHis(itemVO);
                    itemMapper.updateItem(itemVO);

                }else if("3".equals(operate)){
                    itemMapper.deleteItemid(itemVO.getItemid());
                }

            }
        }catch(Exception e){
            logger.info("分析处理基础信息的项目信息失败"+e.toString());
        }
    }

    public void sysSETITEM(String data){
        //xml解析器
        Serializer serializer = new Persister();
        try{
            //代理银行信息对象
            SetItem setitem = serializer.read(SetItem.class, new StringReader(data));
            if(setitem!=null && setitem.getItem()!=null && setitem.getItem().size()>0){
                for(SetItemDTO item:setitem.getItem()){
                    if(item!=null && item.getState()!=null && !item.getState().trim().equals("") && item.getItemid()!=null && !item.getItemid().trim().equals("")){
                        ItemVO itemVO = new ItemVO(item);
                        itemVO.setWritetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                        if ("1".equals(item.getState()) || "2".equals(item.getState())) {
                            itemVO.setIsenable(1);
                        } else if ("3".equals(item.getState())) {
                            itemVO.setIsenable(0);
                        } else {
                            itemVO.setIsenable(null);
                        }
                        if (itemVO.getIsenable() != null) {
                            if(itemMapper.selectItemidCount(itemVO.getItemid())>0){
                                itemMapper.updateItem(itemVO);
                            }else{
                                itemMapper.saveItem(itemVO);
                            }
                        }
                    }
                }
            }
        }catch(Exception e){
            logger.info("分析处理基础信息的项目失败"+e.toString());
        }
    }

    @Resource
    private UnitVsItemMapper unitVsItemMapper;

    public void sysSETUNITVSITEM(String data){
        //xml解析器
        Serializer serializer = new Persister();
        try{
            //代理银行信息对象
            SetUnitVsItem setunitvsitem = serializer.read(SetUnitVsItem.class, new StringReader(data));
            if(setunitvsitem!=null && setunitvsitem.getUnitvsitem()!=null && setunitvsitem.getUnitvsitem().size()>0){
                for(SetUnitVsItemDTO unitvsitem:setunitvsitem.getUnitvsitem()){
                    if(unitvsitem!=null && unitvsitem.getState()!=null && !unitvsitem.getState().trim().equals("") && unitvsitem.getRelationid()!=null && !unitvsitem.getRelationid().trim().equals("")){
                        UnitvsitemVO unitvsitemVO = new UnitvsitemVO(unitvsitem);
                        unitvsitemVO.setWritetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                        if ("1".equals(unitvsitem.getState()) || "2".equals(unitvsitem.getState())) {
                            unitvsitemVO.setIsenable(1);
                        } else if ("3".equals(unitvsitem.getState())) {
                            unitvsitemVO.setIsenable(0);
                        } else {
                            unitvsitemVO.setIsenable(null);
                        }
                        if (unitvsitemVO.getIsenable() != null) {
                            if(unitVsItemMapper.selectRelationidCount(unitvsitemVO.getRelationid())>0){
                                unitVsItemMapper.updateUnitItem(unitvsitemVO);
                            }else{
                                unitVsItemMapper.saveUnitItem(unitvsitemVO);
                            }
                        }
                    }
                }
            }
        }catch(Exception e){
            logger.info("分析处理基础信息的单位与项目挂接失败"+e.toString());
        }
    }

    @Resource
    private KeyWordMapper keyWordMapper;

    public void sysSETKEYWORD(String data){
        //xml解析器
        Serializer serializer = new Persister();
        try{
            //字轨信息对象
            SetKeyWord setkeyword = serializer.read(SetKeyWord.class, new StringReader(data));
            if(setkeyword!=null && setkeyword.getKeyword()!=null && setkeyword.getKeyword().size()>0){
                for(SetKeyWordDTO keyword:setkeyword.getKeyword()){
                    if(keyword!=null && keyword.getState()!=null && !keyword.getState().trim().equals("") && keyword.getItemid()!=null && !keyword.getItemid().trim().equals("")){
                        KeyWordVO keyWordVO = new KeyWordVO(keyword);
                        keyWordVO.setWritetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                        keyWordVO.setIsenable(1);
                        if(keyword.getState().trim().equals("1")){
                            if(keyWordMapper.selectItemIdCount(keyWordVO.getItemid())>0){
                                keyWordMapper.updateIsenable(keyWordVO);
                            }else{
                                keyWordMapper.saveKeyWord(keyWordVO);
                            }
                            break;
                        }else if (keyword.getState().trim().equals("2")){
                            keyWordMapper.updateKeyWord(keyWordVO);
                            break;
                        }else if (keyword.getState().trim().equals("3")){
                            keyWordVO.setIsenable(0);
                            keyWordMapper.updateIsenable(keyWordVO);
                            break;
                        }

                    }
                }
            }
        }catch(Exception e){
            logger.info("分析处理基础信息的字轨失败"+e.toString());
        }
    }

    @Resource
    private PayWayMapper payWayMapper;
    public void sysSETPAYWAY(String data){
        //xml解析器
        Serializer serializer = new Persister();
        try{
            //缴款方式信息对象
            SetPayWay setpayway = serializer.read(SetPayWay.class, new StringReader(data));
            if(setpayway!=null && setpayway.getPayway()!=null && setpayway.getPayway().size()>0){
                for(SetPayWayDTO payway:setpayway.getPayway()){
                    if(payway!=null && payway.getState()!=null && !payway.getState().trim().equals("") && payway.getPaywayid()!=null && !payway.getPaywayid().trim().equals("")){
                        PayWayVO payWayVO = new PayWayVO(payway);
                        payWayVO.setIsenable(1);
                        payWayVO.setWritetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                        if(payway.getState().trim().equals("1")){
                            if(payWayMapper.selectPaywayidCount(payWayVO.getPaywayid())>0){
                                payWayMapper.updateIsenable(payWayVO);
                            }else{
                                payWayMapper.savePayWay(payWayVO);
                            }
                            break;
                        }else if (payway.getState().trim().equals("2")){
                            payWayMapper.savePayWay(payWayVO);
                            break;
                        }else if (payway.getState().trim().equals("3")){
                            payWayVO.setIsenable(0);
                            payWayMapper.updateIsenable(payWayVO);
                            break;
                        }
                    }
                }
            }
        }catch(Exception e){
            logger.info("分析处理基础信息的缴款方式失败"+e.toString());
        }
    }

    @Resource
    private PayerTypeMapper payerTypeMapper;
    public void sysSETPAYERTYPE(String data){
        //xml解析器
        Serializer serializer = new Persister();
        try{
            //缴款方式信息对象
            SetPayerType setpayertype = serializer.read(SetPayerType.class, new StringReader(data));
            if(setpayertype!=null && setpayertype.getPayertype()!=null && setpayertype.getPayertype().size()>0){
                for(SetPayerTypeDTO payertype:setpayertype.getPayertype()){
                    if(payertype!=null && payertype.getState()!=null && !payertype.getState().trim().equals("") && payertype.getPayertypeid()!=null && !payertype.getPayertypeid().trim().equals("")){
                        PayerTypeVO payerTypeVO = new PayerTypeVO(payertype);
                        payerTypeVO.setIsenable(1);
                        payerTypeVO.setWritetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                        if(payertype.getState().trim().equals("1")){
                            if(payerTypeMapper.selectPayTypeIdCount(payerTypeVO.getPayertypeid())>0){
                                payerTypeMapper.updateIsenable(payerTypeVO);
                            }else{
                                payerTypeMapper.savePayType(payerTypeVO);
                            }
                            break;
                        }else if (payertype.getState().trim().equals("2")){
                            payerTypeMapper.updatePayType(payerTypeVO);
                            break;
                        }else if (payertype.getState().trim().equals("3")){
                            payerTypeVO.setIsenable(0);
                            payerTypeMapper.updateIsenable(payerTypeVO);
                            break;
                        }
                    }
                }
            }
        }catch(Exception e){
            logger.info("分析处理基础信息的缴款类型失败"+e.toString());
        }
    }

    /**
     * 获取项目编号名称
     * @param unitid
     * @return
     */
    public List<Item> findUnitVsItem(Long unitid) {
        return  itemMapper.findUnitVsItem(unitid);
    }

    public BankVO selectBankById(int bankId) {
        return bankMapper.selectBankById(bankId);
    }

    public Canton selectCantonById(int id) {
        return cantonMapper.selectCantonById(id);
    }
}